package com.mvcMovie.handler;

import com.mvcMovie.bean.Movie;
import com.mvcMovie.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/root")
public class RootHandler {

    @Autowired
    private MovieService movieService;

    @GetMapping("/list")
    public String list(Model model){
        List<Movie> movies = movieService.getAllMovie();
        model.addAttribute("movies",movies);

        return "root_list";
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        movieService.deleteMovie(id);
        return "redirect:/root/list";
    }

    @GetMapping("/detail/{id}")
    public String detail(
            @PathVariable("id") Integer id,
            Model model){
        Movie movie = movieService.getMovie(id);
        model.addAttribute("movie",movie);
        return "root_detail";
    }

    @GetMapping("/modify/{id}")
    public String modify(
            @PathVariable("id") Integer id,
            Model model){
        Movie movie = movieService.selectById(id);
        model.addAttribute("movie",movie);
        return "root_edit";
    }

    @PutMapping("/modify")
    public String modifysave(
            @RequestParam("id") Integer id,
            @RequestParam("movieName") String movieName,
            @RequestParam("movieScore") String movieScore){
        movieService.updateMovie(movieName, Double.valueOf(movieScore),id);
        return "redirect:/root/list";
    }

    @PostMapping("/addsave")
    public String add(@RequestParam("id") Integer id,
                      @RequestParam("movieName") String movieName,
                      @RequestParam("movieScore") String movieScore){
        Movie movie = new Movie(id,movieName,Double.valueOf(movieScore));
        movieService.addMovie(movie);
        return "redirect:/root/list";
    }
}
